package com.hxqc.basic.common;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class DateUtil {

	private static SimpleDateFormat year_format = new SimpleDateFormat("yyyy");

	public static SimpleDateFormat default_format = new SimpleDateFormat(
			"yyyy-MM-dd");
	
	public static SimpleDateFormat common_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static SimpleDateFormat time_format = new SimpleDateFormat(
			"yyyyMMddHHmmss");

	protected static Log log = LogFactory.getLog(DateUtil.class);

	/**
	 * 得到当前时间,返回long型
	 * 
	 * @return String
	 */
	public static long generateLongTime() {
		Date dt = new Date();
		return dt.getTime();
	}

	/**
	 * 得到当前时间,格式为yyyyMMddhhmmss
	 * 
	 * @return String
	 */
	public static String generateTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		return format.format(new Date());
	}

	/**
	 * 根据格式生成当前日期时间
	 * 
	 * @param formatStr
	 * @return
	 */
	public static String generateDateTime(String formatStr) {
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		return format.format(new Date());
	}
	
	public static String generateDateTimeAddHour(int addHour,String formatstr){
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, addHour);
		SimpleDateFormat format = new SimpleDateFormat(formatstr);
		return format.format(cal.getTime());
	}
	/**
	 * 根据格式生成日期时间
	 * @param date
	 * @param formatStr
	 * @return
	 */
    public static String generateDateTime(Date date,String formatStr){
    	SimpleDateFormat format = new SimpleDateFormat(formatStr);
		return format.format(date);
    }
	/**
	 * 根据yyyy-MM-dd得到月份
	 * 
	 * @param dateString
	 *            String
	 * @return int
	 */
	public static int getMonthFromYear(String dateString) {
		Date date = string2Date(dateString);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		System.out.println("calendar.setTime::::"+(calendar.get(Calendar.WEEK_OF_YEAR)));
		return calendar.get(Calendar.MONTH) + 1;
	}

	/**
	 * 得到指定年的所有天数
	 * 
	 * @param year
	 *            String
	 * @return day int
	 */
	public static int getDayFromYear(String year) {
		Date date;
		int day = 0;
		try {
			date = year_format.parse(year);
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			day = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
		} catch (ParseException e) {
			log.error("", e);
		}
		return day;
	}

	/**
	 * 返回下一年_格式yyyy
	 * 
	 * @return int
	 */
	public static int getNextYear() {
		return new GregorianCalendar().get(Calendar.YEAR) + 1;
	}

	/**
	 * 获取某年第一天日期_格式yyyy-MM-dd
	 * 
	 * @param year
	 *            年份
	 * @return String
	 */
	public static String getCurrYearFirstDay(int year) {
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		Date currYearFirst = calendar.getTime();
		return default_format.format(currYearFirst);
	}

	/**
	 * 根据一个日期，返回是星期几的数字_星期一:1....星期六:6,星期天:7，
	 * 注意：日期输错，不会报错，例如：2月30或31号
	 * 
	 * @param date
	 *            日期值
	 * @return int
	 */
	public static int getWeek(Date date) {

		Calendar c = Calendar.getInstance();
		c.setTime(date);
		System.out.println("c.get(Calendar.DAY_OF_WEEK)::::"+c.get(Calendar.DAY_OF_WEEK));
		int iDay = 0;
		if (c.get(Calendar.DAY_OF_WEEK) == 1) {
			iDay = 7;
		} else {
			iDay = c.get(Calendar.DAY_OF_WEEK) - 1;
		}
		return iDay;
	}
	
	/**
	 * 根据一个日期，返回是星期几的数字_星期一:1....星期六:6,星期天:7，
	 * 注意：日期输错，不会报错，例如：2月30或31号
	 * 
	 * @param dateString
	 *            String
	 * @return int
	 */
	public static int getWeek(String dateString) {
		Date date = string2Date(dateString);
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		int iDay = 0;
		if (c.get(Calendar.DAY_OF_WEEK) == 1) {
			iDay = 7;
		} else {
			iDay = c.get(Calendar.DAY_OF_WEEK) - 1;
		}
		return iDay;
	}

	/**
	 * 根据一个日期,传入指定天数,想要返回长度,得到String
	 * 
	 * @param inDate
	 *            日期
	 * @param days
	 *            天数
	 * @param _iType
	 *            inDate长度
	 * @return String
	 */
	public static String getDateByAddDays(String inDate, int days, int _iType) {
		Date dateStr = string2Date(inDate);
		Date tempDate = getDateByAddDays(dateStr, days);
		return date2String(tempDate, _iType);
	}

	/**
	 * 根据Date日期,传入返回长度,得到String
	 * 
	 * @param date
	 *            Date
	 * @param _iType
	 *            返回String长度
	 * @return String
	 */
	public static String date2String(Date date, int _iType) {
		String strTemp = time_format.format(date);
		SimpleDateFormat formatter = null;
		switch (_iType) {
		case 0: // yyyymmdd
			strTemp = strTemp.substring(0, 8);
			break;
		case 4:// yyyy
			strTemp = strTemp.substring(0, 4);
			break;
		case 6: // yymmdd
			strTemp = strTemp.substring(2, 8);
			break;
		case 8: // yyyymmdd
			strTemp = strTemp.substring(0, 8);
			break;
		case 14:
			// yyyyMMddHHmmss 格式
			break;
		case 10: // yyyy-mm-dd
			formatter = new SimpleDateFormat("yyyy-MM-dd");
			strTemp = formatter.format(date);
			break;
		case 17:
			formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			strTemp = formatter.format(date);
			break;
		case 19: // yyyy-mm-dd HH:mm:ss
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			strTemp = formatter.format(date);
			break;
		case -6: // HHmmss
			strTemp = strTemp.substring(8);
			break;
		case -8: // HH:mm:ss
			formatter = new SimpleDateFormat("HH:mm:ss");
			strTemp = formatter.format(date);
			break;
		default:
			break;
		}
		return strTemp;
	}

	/**
	 * 获得指定日期前后的日期，返回日期型值
	 * 
	 * @param inDate
	 *            指定的日期
	 * @param days
	 *            加减天数
	 * @return Date
	 * 
	 */
	public static Date getDateByAddDays(Date inDate, int days) {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(inDate);
		calendar.add(Calendar.DATE, days);
		return calendar.getTime();
	}
	
	public static String getDateByAddDays(String formatStr, int days) {
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, days);
		return format.format(calendar.getTime());
	}
	
	
	public static Date getDateByAddMinutes(Date inDate, int minutes) {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(inDate);
		calendar.add(Calendar.MINUTE, minutes);
		return calendar.getTime();
	}
	

	/**
	 * 获得指定日期前后的日期，返回日期格式
	 * 
	 * @param inDate
	 *            指定日期
	 * @param month
	 *            加减月数
	 * @return
	 */
	public static Date getDateByAddMonth(Date inDate, int month) {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(inDate);
		calendar.add(Calendar.MONTH, month);
		return calendar.getTime();
	}

	/**
	 * 当前日期的前后日期，返回字符串格式 yyyyMMddHHmmss
	 * 
	 * @param month
	 *            加减月数
	 * @return
	 */
	public static String getCurrentByAddMonth(int month) {
		Date d = getDateByAddMonth(new Date(), month);

		return date2String(d, 14);
	}

	/**
	 * 将日期字符串转换成日期型，日期格式为"yyyy-MM-dd"
	 * 
	 * @param dateString
	 *            指定的日期字符串，格式为yyyyMMdd 或者yyyy-MM-dd
	 * @return Date
	 * @author lijunchen
	 */
	public final static Date string2Date(String dateString) {
		if (dateString == null || dateString.trim().length() == 0) {
			return new Date(0);
		}
		
		// 处理不规范格式，例如：2013-1-2
		if (dateString.indexOf("-") > 0) {
			String month = dateString.substring(dateString.indexOf("-")+1,dateString.lastIndexOf("-"));
			if(month.length()==1){
				dateString =dateString.replace("-"+month+"-", "-0"+month+"-");
			}
			String day = dateString.substring(dateString.lastIndexOf("-")+1,dateString.length());
			if(day.length()==1){
				dateString = dateString.substring(0,dateString.lastIndexOf("-")+1)+"0"+day;
			}
			// System.out.println(dateString);
		}
		
		try {
			String strFormat = "";
			switch (dateString.length()) {
			case 4:
				strFormat = "yyyy";
				break;
			case 6: // yymmdd
				strFormat = "yyMMdd";
				break;
			case 8: // yyyymmdd
				strFormat = "yyyyMMdd";
				break;
			case 10: // yyyy-mm-dd
				strFormat = "yyyy-MM-dd";
				break;
			case 14:
				strFormat = "yyyyMMddHHmmss";
				break;
			default:
				strFormat = "yyyy-MM-dd HH:mm:ss";
			}
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(strFormat);
			// 这里没有做非法日期的判断，比如：＂2007-05-33＂
			java.util.Date timeDate = simpleDateFormat.parse(dateString);
			return timeDate;
		} catch (Exception e) {
			return new Date(0);
		}
	}

	/**
	 * 得到两个时间的差值，单位是小时
	 * 
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public static double getHourBetweenDates(Date beginDate, Date endDate) {

		long l1 = endDate.getTime();
		long l2 = beginDate.getTime();

		double cc = l1 - l2;
		return cc / (60 * 60 * 1000);
	}

	/**
	 * 得到两个时间的差值，单位是分钟
	 * 
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public static double getMinuteBetweenDates(Date beginDate, Date endDate) {

		double cc = endDate.getTime() - beginDate.getTime();
		return cc / (60 * 1000);
	}

	/**
	 * 根据Date日期,传入返回长度,得到String
	 * 
	 * @param date
	 *            Date
	 * @param _iType
	 *            返回String长度
	 * @return String
	 */
	public static String longDate2String(long lDate, int _iType) {

		Date date = new Date(lDate);
		String strTemp = time_format.format(date);
		SimpleDateFormat formatter = null;
		switch (_iType) {
		case 0: // yyyymmdd
			strTemp = strTemp.substring(0, 8);
			break;
		case 4:// yyyy
			strTemp = strTemp.substring(0, 4);
			break;
		case 6: // yymmdd
			strTemp = strTemp.substring(2, 8);
			break;
		case 8: // yyyymmdd
			strTemp = strTemp.substring(0, 8);
			break;
		case 10: // yyyy-mm-dd
			formatter = new SimpleDateFormat("yyyy-MM-dd");
			strTemp = formatter.format(date);
			break;
		case -6: // HHmmss
			strTemp = strTemp.substring(8);
			break;
		case -8: // HH:mm:ss
			formatter = new SimpleDateFormat("HH:mm:ss");
			strTemp = formatter.format(date);
			break;
		default:
			break;
		}
		return strTemp;
	}

	public static int getDaysBetween(Date bDate, Date eDate) {
		Calendar d1 = new GregorianCalendar();
		d1.setTime(bDate);
		Calendar d2 = new GregorianCalendar();
		d2.setTime(eDate);
		int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
		int y2 = d2.get(Calendar.YEAR);
		if (d1.get(Calendar.YEAR) != y2) {
			d1 = (Calendar) d1.clone();
			do {
				days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);// 得到当年的实际天数
				d1.add(Calendar.YEAR, 1);
			} while (d1.get(Calendar.YEAR) != y2);
		}
		return days;
	}

	/**
	 * 返回本年份_格式yyyy
	 * 
	 * @return int
	 */
	public static int getCurrYear() {
		return new GregorianCalendar().get(Calendar.YEAR);
	}
	
	/**
	 * 获得月份英文缩写
	 * 
	 * @param sMonth
	 *            String
	 * @return String
	 */
	public static String getMonthEnglishName(String sMonth) {

		String[] arrMonth = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
		
		int iMonth = 0;
		String sRet = "";
		try {
			iMonth = Integer.parseInt(sMonth);
			if (iMonth >= 1 && iMonth <= 12) {
				sRet = arrMonth[iMonth -1];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sRet;
	}
	public static Date StringToDate(String dateStr, String formatStr) {
		DateFormat dd = new SimpleDateFormat(formatStr);
		Date date = null;
		try {
			date = dd.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	public static int getBetweenDayNumber(Date dateA, Date dateB) {
		long dayNumber = 0;
		// 1小时=60分钟=3600秒=3600000
		long mins = 60L * 1000L;
		// long day= 24L * 60L * 60L * 1000L;计算天数之差
		dayNumber = (dateB.getTime() - dateA.getTime()) / mins;
		return (int) dayNumber;
	}
	
	/**
	 * @param date1
	 *            需要比较的时间 不能为空(null),需要正确的日期格式
	 * @param date2
	 *            被比较的时间 为空(null)则为当前时间
	 * @param stype
	 *            返回值类型 0为多少天，1为多少个月，2为多少年
	 * @return
	 */
	@SuppressWarnings("unused")
	public static int compareDate(String date1, String date2, int stype) {
		int n = 0;

		String[] u = { "天", "月", "年" };
		String formatStyle = stype == 1 ? "yyyy-MM" : "yyyy-MM-dd";

		date2 = date2 == null ? DateUtil.getCurrentDate() : date2;

		DateFormat df = new SimpleDateFormat(formatStyle);
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		try {
			c1.setTime(df.parse(date1));
			c2.setTime(df.parse(date2));
		} catch (Exception e3) {
			System.out.println("wrong occured");
		}
		// List list = new ArrayList();
		while (!c1.after(c2)) { // 循环对比，直到相等，n 就是所要的结果
			// list.add(df.format(c1.getTime())); // 这里可以把间隔的日期存到数组中 打印出来
			n++;
			if (stype == 1) {
				c1.add(Calendar.MONTH, 1); // 比较月份，月份+1
			} else {
				c1.add(Calendar.DATE, 1); // 比较天数，日期+1
			}
		}

		n = n - 1;

		if (stype == 2) {
			n = (int) n / 365;
		}

		//System.out.println(date1 + " -- " + date2 + " 相差多少" + u[stype] + ":" + n);
		return n;
	}

	/**
	 * 得到当前日期
	 * 
	 * @return
	 */
	public static String getCurrentDate() {
		Calendar c = Calendar.getInstance();
		Date date = c.getTime();
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
		return simple.format(date);
	}
	
	public static void main(String[] args) {
		System.out.println(Double.parseDouble(DateUtil.date2String(new Date(), 17)));
	}
}
